package com.linkoog.devtools.intellij.ui.table.cell_editor;

import com.intellij.ui.DocumentAdapter;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.table.TableCellEditor;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;

public class StringDocumentTableCellEditor extends AbstractCellEditor implements TableCellEditor {
    private Document myDocument;
    private final StringDocumentHandler documentHandler;

    public StringDocumentTableCellEditor(StringDocumentHandler documentHandler) {
        this.documentHandler = documentHandler;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        JTextField textField = new JTextField();
        textField.setBorder(JBUI.Borders.empty(1));
        myDocument = textField.getDocument();
        if (documentHandler != null){
            myDocument.addDocumentListener(new DocumentAdapter(){

                @Override
                protected void textChanged(@NotNull DocumentEvent event) {
                    documentHandler.documentChanged(event, table, value, getCellEditorValue(), row, column);
                }
            });
        }
        textField.setText((String)value);
        return textField;
    }

    @Override
    public Object getCellEditorValue() {
        try {
            return myDocument.getText(0, myDocument.getLength());
        } catch (BadLocationException ignored) {
        }
        return "";
    }





}